<template>
  <el-drawer v-model="drawerVisible" :title="drawerTitle" size="60%" direction="rtl">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
      <el-form-item label="资料分类" prop="category">
        <el-select v-model="formData.category" placeholder="请选择分类" style="width: 100%">
          <el-option label="售前资料" value="presale" />
          <el-option label="验收资料" value="acceptance" />
          <el-option label="技术资料" value="technical" />
          <el-option label="其他资料" value="other" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="资料名称" prop="name">
        <el-input v-model="formData.name" :placeholder="isEdit ? '请输入资料名称' : '将自动从文件名提取'" />
      </el-form-item>
      
      <el-form-item label="资料类型" prop="type">
        <el-select v-model="formData.type" :placeholder="isEdit ? '请选择资料类型' : '将自动从文件类型提取'" style="width: 100%">
          <el-option label="Word文档" value="word" />
          <el-option label="PDF文档" value="pdf" />
          <el-option label="Excel表格" value="excel" />
          <el-option label="PPT演示" value="ppt" />
          <el-option label="图片" value="image" />
          <el-option label="视频" value="video" />
          <el-option label="压缩包" value="zip" />
          <el-option label="其他" value="other" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="版本号" prop="version">
        <el-input v-model="formData.version" placeholder="如：v1.0.0" />
      </el-form-item>
      
      <el-form-item label="文件上传" prop="fileUpload">
        <el-upload
          ref="uploadRef"
          v-model:file-list="fileList"
          :action="uploadUrl"
          :auto-upload="false"
          :data="uploadData"
          :disabled="formLoading"
          :limit="1"
          :on-change="handleFileChange"
          :on-error="submitFormError"
          :on-exceed="handleExceed"
          :on-success="submitFormSuccess"
          :http-request="httpRequest"
          accept=".doc,.docx,.pdf,.xls,.xlsx,.ppt,.pptx,.jpg,.png,.gif,.mp4,.zip,.rar"
          drag
          class="upload-area"
        >
          <Icon icon="ep:upload-filled" size="60" class="upload-icon" />
          <div class="upload-text">
            <p v-if="!isEdit">将文件拖到此处，或 <em>点击上传</em></p>
            <p v-else>重新上传文件（可选）</p>
            <p class="upload-tip">支持 doc/docx/pdf/xls/xlsx/ppt/pptx/jpg/png/gif/mp4/zip/rar 等格式</p>
          </div>
        </el-upload>
        
        <!-- 编辑模式下显示当前文件信息 -->
        <div v-if="isEdit && formData.fileUrl" class="current-file">
          <el-alert
            title="当前文件"
            type="info"
            :closable="false"
            show-icon
          >
            <template #default>
              <div class="file-info">
                <span>{{ originalFileName }}</span>
                <span class="file-size">({{ formData.size }})</span>
                <el-button 
                  type="primary" 
                  link 
                  @click="downloadCurrentFile"
                  class="ml-2"
                >
                  <Icon icon="ep:download" />下载
                </el-button>
              </div>
            </template>
          </el-alert>
        </div>
      </el-form-item>
      
      <el-form-item label="备注">
        <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="drawer-footer">
        <el-button @click="drawerVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="formLoading">
          {{ isEdit ? '更新' : '保存' }}
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { useUpload } from '@/components/UploadFile/src/useUpload'
import { MaterialApi, type MaterialVO } from '@/api/agent/manage/material'

defineOptions({ name: 'MaterialUpload' })

const message = useMessage()
const { t } = useI18n()

const drawerVisible = ref(false)
const formLoading = ref(false)
const formRef = ref<FormInstance>()
const uploadRef = ref()
const fileList = ref([])
const isEdit = ref(false)
const originalFileName = ref('')
const hasFileSelected = ref(false) // 添加文件选择状态
const productVersion = ref('v1.0.0') // 产品版本号

const formData = reactive({
  id: undefined,
  name: '',
  type: '',
  category: '',
  version: '',
  remark: '',
  relatedId: 0,
  relatedType: 'product',
  size: '',
  fileUrl: ''
})

const uploadData = ref({ path: '' })
const { uploadUrl, httpRequest } = useUpload()

// 动态标题
const drawerTitle = computed(() => {
  return isEdit.value ? '编辑资料' : '上传资料'
})

// 动态表单验证规则
const formRules = computed((): FormRules => {
  const rules: FormRules = {
    category: [{ required: true, message: '请选择资料分类', trigger: 'change' }],
    name: [{ required: true, message: '请输入资料名称', trigger: 'blur' }],
    type: [{ required: true, message: '请选择资料类型', trigger: 'change' }],
    version: [{ required: true, message: '请输入版本号', trigger: 'blur' }]
  }
  
  // 新增模式下文件上传为必填
  if (!isEdit.value) {
    rules.fileUpload = [
      {
        validator: (rule, value, callback) => {
          if (!hasFileSelected.value) {
            callback(new Error('请上传文件'))
          } else {
            callback()
          }
        },
        trigger: 'change'
      }
    ]
  }
  
  return rules
})

/** 文件类型映射 */
const getFileType = (fileName: string): string => {
  const ext = fileName.split('.').pop()?.toLowerCase()
  const typeMap: Record<string, string> = {
    'doc': 'word',
    'docx': 'word',
    'pdf': 'pdf',
    'xls': 'excel',
    'xlsx': 'excel',
    'ppt': 'ppt',
    'pptx': 'ppt',
    'jpg': 'image',
    'jpeg': 'image',
    'png': 'image',
    'gif': 'image',
    'mp4': 'video',
    'avi': 'video',
    'mov': 'video',
    'zip': 'zip',
    'rar': 'zip'
  }
  return typeMap[ext || ''] || 'other'
}

/** 提取文件名（去除扩展名） */
const getFileName = (fileName: string): string => {
  return fileName.replace(/\.[^/.]+$/, '')
}

/** 处理文件变化 */
const handleFileChange = (file: any) => {
  if (file.raw) {
    hasFileSelected.value = true // 标记已选择文件
    
    // 只在新增模式下自动提取文件信息
    if (!isEdit.value) {
      // 自动提取文件名
      const fileName = getFileName(file.name)
      formData.name = fileName
      
      // 自动识别文件类型
      const fileType = getFileType(file.name)
      formData.type = fileType
    }
    
    // 计算文件大小
    formData.size = `${(file.raw.size / 1024 / 1024).toFixed(2)}MB`
    
    // 设置上传路径
    uploadData.value.path = `materials/${formData.category}/${file.name}`
    
    // 触发表单验证
    formRef.value?.validateField('fileUpload')
  }
}

/** 打开抽屉 - 新增模式 */
const open = (category: string, relatedId: number, version?: string) => {
  isEdit.value = false
  formData.category = category
  formData.relatedId = relatedId
  productVersion.value = version || 'v1.0.0' // 设置产品版本号
  resetForm()
  drawerVisible.value = true
}

/** 打开抽屉 - 编辑模式 */
const openEdit = (material: MaterialVO) => {
  isEdit.value = true
  Object.assign(formData, material)
  originalFileName.value = material.name || ''
  hasFileSelected.value = true // 编辑模式下认为已有文件
  resetForm(false) // 不清空表单数据
  drawerVisible.value = true
}

defineExpose({ open, openEdit })

/** 下载当前文件 */
const downloadCurrentFile = () => {
  if (formData.fileUrl) {
    window.open(formData.fileUrl, '_blank')
  } else {
    message.warning('文件地址不存在')
  }
}

/** 提交表单 */
const submitForm = async () => {
  const valid = await formRef.value?.validate()
  if (!valid) return
  
  formLoading.value = true
  
  // 如果有新文件上传，先上传文件
  if (fileList.value.length > 0) {
    uploadRef.value?.submit()
  } else {
    // 编辑模式下没有新文件，直接保存
    await saveMaterialInfo()
  }
}

/** 保存资料信息 */
const saveMaterialInfo = async (fileUrl?: string) => {
  try {
    const materialData: MaterialVO = {
      ...formData,
      fileUrl: fileUrl || formData.fileUrl // 使用新上传的文件URL或保持原有URL
    }
    
    if (isEdit.value) {
      await MaterialApi.updateMaterial(materialData)
      message.success('资料更新成功')
    } else {
      await MaterialApi.createMaterial(materialData)
      message.success('资料上传成功')
    }
    
    drawerVisible.value = false
    emit('success')
  } catch (error) {
    console.error('保存资料信息失败:', error)
    message.error('保存资料信息失败')
  } finally {
    formLoading.value = false
  }
}

/** 文件上传成功 */
const emit = defineEmits(['success'])
const submitFormSuccess = async (response: any) => {
  await saveMaterialInfo(response.data) // 传入新的文件URL
}

/** 上传失败 */
const submitFormError = () => {
  message.error('文件上传失败，请重试')
  formLoading.value = false
}

/** 文件数量超限 */
const handleExceed = () => {
  message.error('最多只能上传一个文件')
}

/** 重置表单 */
const resetForm = (clearData = true) => {
  if (clearData) {
    Object.assign(formData, {
      id: undefined,
      name: '',
      type: '',
      version: productVersion.value, // 使用产品版本号作为默认值
      remark: '',
      size: '',
      fileUrl: ''
    })
    hasFileSelected.value = false // 重置文件选择状态
  }
  
  formLoading.value = false
  uploadRef.value?.clearFiles()
  fileList.value = []
  
  if (clearData) {
    formRef.value?.resetFields()
  }
}
</script>

<style lang="scss" scoped>
.upload-area {
  width: 100%;
  
  :deep(.el-upload) {
    width: 100%;
  }
  
  :deep(.el-upload-dragger) {
    width: 100%;
    height: 200px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
}

.upload-icon {
  color: #409eff;
  margin-bottom: 16px;
}

.upload-text {
  text-align: center;
  
  p {
    margin: 0;
    color: #606266;
    
    &.upload-tip {
      font-size: 12px;
      color: #909399;
      margin-top: 8px;
    }
    
    em {
      color: #409eff;
      font-style: normal;
    }
  }
}

.current-file {
  margin-top: 12px;
  
  .file-info {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .file-size {
      color: #909399;
      font-size: 12px;
    }
  }
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px;
  border-top: 1px solid #e4e7ed;
}
</style>